#include <iostream>
#include <memory>

int main(int argc, char *argv[])
{
    // 使用make_shared创建指向一个空对象
    std::shared_ptr<int> p1 = std::make_shared<int>();
    *p1 = 82; // 为创建的对象赋值
    std::cout << "p1 = "<<*p1 << std::endl;

    std::cout << "p1 reference count:"<<p1.use_count() << std::endl;

    // 指向同一指针的shared_ptr
    std::shared_ptr<int> p2(p1);

    std::cout << "p1 reference count:"<<p1.use_count() << std::endl;
    std::cout << "p2 reference count:"<<p2.use_count() << std::endl;

    // 赋值一个新值
    *p2 = 100;
    // 查看新值
    std::cout << "p1 = "<<*p1 << std::endl;
    std::cout << "p2 = "<<*p2 << std::endl;

    // 比较shared_ptr，即是比较里面的指针是否指向同一个对象
    if (p1 == p2) {
        std::cout << "p1 and p2 has the same pointer!" << std::endl;
    }

    // 无参数调用reset
    p1.reset();
    std::cout << "p1 reference count after reset():"<<p1.use_count() << std::endl;

    std::cout << "p2 = "<<*p2 << std::endl;
    std::cout << "p2 reference count:"<<p2.use_count() << std::endl;

    // 有参数的reset
    p1.reset(new int(200));
    std::cout << "p1 reference count after reset(param):"<<p1.use_count() << std::endl;
    std::cout << "p1 = "<<*p1 << std::endl;
    std::cout << "p2 = "<<*p2 << std::endl;

    p1 = nullptr;
    std::cout << "p1 reference count after nullptr:"<<p1.use_count() << std::endl;
    // shared_ptr的operator bool()
    if (!p1) {
        std::cout << "p1 is nullptr!" << std::endl;
    }

    return 0;
}
